import asyncio
import aio_pika

from config import RABBITMQ_URI


async def topic_consumer(queue_name: str, consumer_id: str):
    """
    监听指定队列的消费者
    :param queue_name: 要监听的队列名称
    :param consumer_id: 消费者标识，用于区分不同消费者
    """
    # 建立连接
    connection = await aio_pika.connect_robust(RABBITMQ_URI)
    channel = await connection.channel()

    # 开启公平调度，确保消费者处理完一条消息再接收下一条
    await channel.set_qos(prefetch_count=1)

    # 声明要监听的队列（与生产者中创建的队列保持一致）
    queue = await channel.declare_queue(
        queue_name,
        durable=True,
        auto_delete=False
    )

    # 消息处理函数
    async def on_message(message: aio_pika.IncomingMessage):
        # 自动确认消息（处理完成后从队列中删除）
        async with message.process():
            message_content = message.body.decode("utf-8")
            print(f"[Consumer {consumer_id}] Received message: {message_content}")
            print(f"[Consumer {consumer_id}] Message routing key: {message.routing_key}")
            print(f"[Consumer {consumer_id}] From queue: {queue_name}\n")

            # 模拟消息处理耗时（根据实际业务逻辑调整）
            await asyncio.sleep(1)

    # 开始消费队列中的消息
    consumer_tag = f"topic_{consumer_id}_{queue_name}"
    await queue.consume(on_message, consumer_tag=consumer_tag)
    print(f"[Consumer {consumer_id}] Started, listening to queue: {queue_name} (tag: {consumer_tag})")

    # 保持消费者运行（无限期阻塞）
    await asyncio.Future()


async def start_all_topic_consumers(queue_prefix="demo.topic.queue-"):
    """启动所有Topic Exchange对应的消费者"""
    # 与setup_topic_exchange中的队列名称对应
    consumer_tasks = [
        topic_consumer(f"{queue_prefix}critical", "CriticalHandler"),
        topic_consumer(f"{queue_prefix}order", "OrderHandler"),
        topic_consumer(f"{queue_prefix}user.login", "UserLoginHandler")
    ]

    # 同时启动所有消费者
    await asyncio.gather(*consumer_tasks)


if __name__ == "__main__":
    # 启动消费者
    asyncio.run(start_all_topic_consumers())
